/*
	Copyright 2009 Joshua Lückers < http://joshualuckers.nl >
	Used the "Send from Gmail (by Google)" extension as example.
			
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
	MA 02110-1301, USA.
 */
function rewriteIRCtoMibbitUrl(inUrl) {
  var retUrl = inUrl;
  retUrl = inUrl.split("/");
	if (retUrl[0] == "irc:") {
		return "http://www.mibbit.com/#" +retUrl[3]+ "@" +retUrl[2];
	}
	else if (retUrl[0] == "ircs:") {
		port = retUrl[3].split(":");
		if (!port[1]) {
			return "https://www.mibbit.com/#" +retUrl[3]+ "@" +retUrl[2]+ ":+6697";
		}
		else {
			return "https://www.mibbit.com/#" +port[0]+ "@" +retUrl[2]+ ":+" +port[1];
		}
	}
}

function rewriteIRCtoMibbit() {
  var result = document.evaluate(
      '//a[contains(@href, "irc:") or contains(@href, "ircs:")]',
      document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

  var item;
  var nodes = [];
  while (item = result.iterateNext()) {
    nodes.push(item);
  }
  
  for (var i = 0; i < nodes.length; i++) {
    var irc_str = nodes[i].getAttribute('href');
    irc_str = rewriteIRCtoMibbitUrl(irc_str);
    nodes[i].setAttribute('href', irc_str);
    nodes[i].setAttribute('target', "_blank");
  }
}
if (window == top) {
  rewriteIRCtoMibbit();
  window.addEventListener("focus", rewriteIRCtoMibbit);
}
